# write by hasaki
# first edit on 2019/01/03
# last change on 2019/01/03
# gateio websocket����
import urllib
import json
import hashlib
import hmac
import gzip
import base64
import time
import random

from websocket import create_connection

class GateWebsocket:
    def __init__(self):
        self.excahnge_name='gateio'
        self.__url=None
        self.__apiKey=None
        self.__secretKey=None

    def setKey(self,url,apiKey,secretKey):
        '''���ⲿ������Կ'''
        self.__url=url
        self.__apiKey=apiKey
        self.__secretKey=secretKey

    def get_sign(self,secret_key, message):
	    h = hmac.new(secret_key.encode(), message, hashlib.sha512)
	    return base64.b64encode(h.digest())

    def gateGet(self,id,method,params):
        if params==None:
            params=[]
        ws = create_connection(self.__url)
        data= { 'id' : id, 'method' : method, 'params' : params}
        js=json.dumps(data)
        ws.send(js)
        return ws.recv()

    def gateRequest(self,id,method,params):
        ws = create_connection(self.__url)
        nonce = int(time.time() * 1000)
        signature = self.get_sign(self.__secretKey, str(nonce))
        data= { 'id' : id, 'method' : 'server.sign' , 'params' : [self.__apiKey, signature, nonce]}
        js=json.dumps(data)
        ws.send(js)
        if method == "server.sign":
            return ws.recv()
        else: 
            ws.recv()
            data= { 'id' : id, 'method' : method, 'params' : params}
            js=json.dumps(data)
            ws.send(js)
            return ws.recv()

    def test(self):
        '''���ڲ������õĺ���'''
        url="wss://ws.gateio.io/v3/"
        key=""
        secret=""
        self.setKey(url,key,secret)
        self.subscribeTicker('EOS_USDT')

    # -------------------------------------------------------------------------------------
    # �������õĺ���
    def connet(self):
        '''����Ƿ������˷�����'''
        return self.gateRequest(random.randint(0,99999),'server.ping',[])

    def serverTime(self):
        '''����ʱ��'''
        return self.gateRequest(random.randint(0,99999),'server.time',[])

    def tick(self,symbol):
        '''����tick�������۸񣬳ɽ��� symbol="EOS_USDT" '''
        return self.gateRequest(random.randint(0,99999),'ticker.query',[symbol,86400])

    def subscribeTicker(self,symbol):
        '''��������tick symbol="EOS_USDT" '''
        return self.gateRequest(random.randint(0,99999),'ticker.subscribe',[symbol])

if __name__=='__main__':
    ws=create_connection("wss://ws.gateio.io/v3/")
    while True:
        ws.send('{"id":12312, "method":"ticker.query", "params":["EOS_USDT", 86400]}')
        print(ws.recv())